package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public BrandDTO queryBrandById(Long id) {
        return new BrandDTO(getById(id));
    }

    @Override
    public List<BrandDTO> queryBrandByIds(List<Long> ids) {
        List<Brand> brands = listByIds(ids);
        return BrandDTO.convertEntityList(brands);
    }

    @Override
    public PageDTO queryBrandPage(String key, Integer page, Integer rows) {
        page = Math.min(page, 100);
        rows = Math.max(rows,5);
        Page<Brand> info = new Page<>(page,rows);
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        query().like(isKeyExists,"name",key)
                .or().like(isKeyExists,"letter",key)
                .page(info);
        List<Brand> records = info.getRecords();
        return new PageDTO(info.getTotal(),info.getPages(),BrandDTO.convertEntityList(records));
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        List<CategoryBrand> categoryBrands = categoryBrandService.query()
                .eq("category_id", id).list();
        List<Long> ids = categoryBrands.stream().map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        List<Brand> list = listByIds(ids);
        return BrandDTO.convertEntityList(list);
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId())).collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean success = updateById(brand);
        if(!success){
            throw new LyException(500,"更新品牌失败");
        }
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",brand.getId());
        success = categoryBrandService.remove(wrapper);
        if(!success){
            throw new LyException(500,"更新品牌失败,删除中间表数据出错");
        }
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId())).collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void deleteBrandById(Long id) {
        removeById(id);
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<CategoryBrand>();
        wrapper.eq("brand_id", id);
        categoryBrandService.removeById(wrapper);
    }
}
